<template>
    <div style="margin: 18px;">
        <el-descriptions border column="3" direction="vertical" title="添加套餐">
            <el-descriptions-item label="套餐图片*" :span="3" align="center">
                <el-upload :action="uploadUrl" method="post" multiple="true" list-type="picture-card"
                    :show-file-list="true" limit="4" :auto-upload="true" :on-preview="handlePictureCardPreview"
                    :on-remove="handleRemove" :on-success="event.handleSuccess" :on-error="event.handleError"
                    :file-list="file">
                    <el-icon>
                        <Plus />
                    </el-icon>
                </el-upload>

                <el-dialog v-model="data.dialogVisible">
                    <img w-full :src="data.dialogImageUrl" width="100%" height="100%" />
                </el-dialog>

            </el-descriptions-item>
            

            <el-descriptions-item label="套餐名称*" :span="1">
                <el-input v-model="data.request.name">

                </el-input>
            </el-descriptions-item>
           
           

            <el-descriptions-item label="类型*" :span="1">
                <el-select v-model="data.pid" clearable placeholder="请选择类型" style="width: 240px" @change="event.select">
                    <el-option v-for="item in data.options" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                </el-select>
            </el-descriptions-item>

            <el-descriptions-item label="产品*" :span="1">
                <div style="display: flex;">

                    <el-button type="primary" @click="event.pro" :disabled="data.isButton">请选择产品</el-button>

                    <div style="padding-left:20px ;">
                        <template v-for="item in data.request.product" :key="item.pname">
                            <el-tag type="danger" style="margin-left: 4px;">{{ item.pname }}￥{{ item.pprice }}</el-tag>
                        </template>
                    </div>

                </div>
            </el-descriptions-item>

            <el-descriptions-item label="折扣*" :span="1">
                <el-select v-model="data.request.discount" :disabled="data.isdiscount" @change="event.discount"
                    clearable placeholder="请选择折扣" style="width: 240px">
                    <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                </el-select>
            </el-descriptions-item>
            <el-descriptions-item label="总价(元)*" :span="1">
                <el-input-number v-model="data.request.total_price" disabled>

                </el-input-number>
            </el-descriptions-item>

            <el-descriptions-item label="套餐数量*(0为不限量)" :span="1">
                <el-input-number v-model="data.request.Stock" :min="0" :max="999">

                </el-input-number>
            </el-descriptions-item>
            <el-descriptions-item label="服务时长*" :span="1">
                <el-input-number v-model="data.request.duration">

                </el-input-number>
            </el-descriptions-item>
            <el-descriptions-item label="开始时间*" :span="1">
                <el-date-picker v-model="data.request.begintime" type="date" placeholder="开始时间" style="width: 100%" />
            </el-descriptions-item>
            <el-descriptions-item label="结束时间*" :span="1">
                <el-date-picker v-model="data.request.endtime" type="date" placeholder="结束时间" style="width: 100%" />
            </el-descriptions-item>
            <el-descriptions-item label="描述*" :span="3">
                <el-input type="textarea" v-model="data.request.explain">

                </el-input>
            </el-descriptions-item>
            <el-descriptions-item label="操作*" :span="3">
                <el-button type="primary" @click="event.Add">
                    新增
                </el-button>
            </el-descriptions-item>
        </el-descriptions>

    </div>

    <div>
        <el-drawer v-model="data.isEdit" title="请选择产品" :before-close="event.handleClose">

            <div>

                <el-skeleton :rows="8" animated :loading="data.isFisrt">

                    <div style="position: absolute; width: 400px; height:700px;">
                        <el-tree ref="treeRef" style="max-width: 600px" :data="data.request.props" show-checkbox
                            default-expand-all node-key="id" highlight-current :props="defaultProps" />
                    </div>
                    <div style="position: absolute;bottom: 20px; width:100%;border-top:1px solid #eee;">
                        <el-button type="primary" style="width: 100%;margin: 10px;" @click="event.save">确定</el-button>
                    </div>

                </el-skeleton>

            </div>

        </el-drawer>
    </div>

</template>

<script setup lang="ts">
import { Get_Product_Type, Get_tree_package, Getpro } from '@/api/product';
import type package_Dto from '@/Dto/Request/product/package';
import Api_Code from '@/Dto/Response/Api_code';
import { dateEquals, dayjs, ElMessage, ElMessageBox } from 'element-plus';
import { onMounted, reactive } from 'vue';
import { ref } from 'vue'
import { ElTree } from 'element-plus'
import { closeloading, startloading } from '@/utils/loading';
import type { UploadFile, UploadFiles } from 'element-plus'
import type { UploadProps } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { Add_Package } from '@/api/product/package';
import { da, el } from 'element-plus/es/locales.mjs';
import { msg } from '@/utils/msg';



const data = reactive<package_Dto>({
    data: [],
    isdiscount: true,
    isEdit: false,
    isButton: true,
    isFisrt: true,
    options: [],
    pid: '',
    dialogImageUrl: {},
    dialogVisible: false,
    request: {
        name: '',
        Stock: '',
        explain:'',
        begintime: '',
        endtime: '',
        discount: '',
        total_price: '',
        props: [],
        pids: [],
        product: [],
        pimg:[],
        delimg: [],
        duration:''
    },
})

const uploadUrl = 'http://localhost:5220/api/product/UploadImage';
const file = ref<UploadFile[]>([]);
//图片放大打开模态框
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    data.dialogImageUrl = uploadFile.url!
    data.dialogVisible = true
}
//移除
const handleRemove: UploadProps['onRemove'] = async (uploadFile, uploadFiles) => {
    //将路径截取修改
    uploadFile.response.data.map((d: string) => [
        data.request.delimg = d.split('images/').pop()
    ])
    const delimgs = data.request.delimg;
    // 遍历数组
    data.request.pimg.forEach((item: any, index: any) => {
        if (item === delimgs) {
            // 使用 splice 删除匹配的元素
            data.request.pimg.splice(index, 1);
        }
    });
    ElMessage.error('移除成功');
}

const defaultProps = {
    children: 'productChildren',
    label: 'name',
    price: 'price',
    id: 'id'
}
//折扣
const options = [
    {
        value: 0.95,
        label: '九五折',
    },
    {
        value: 0.9,
        label: '九折',
    },
    {
        value: 0.85,
        label: '八五折',
    },
    {
        value: 0.8,
        label: '八折',
    },
    {
        value: 0.75,
        label: '七五折',
    },
    {
        value: 0.7,
        label: '七折',
    },
]

const treeRef = ref<InstanceType<typeof ElTree>>()

const event = {

  async  Add(){
       
        if (data.request.pimg == "") {
            ElMessage.error("请至少选择一张照片")
            return
        }
        if (data.request.name == "" || data.request.discount == "" || data.request.total_price == "") {
            ElMessage.error("请填写完整的数据")
            return
        }
        if(data.request.duration==0){
            ElMessage.error("服务时长不能为0")
            return
        }
        startloading()
        const res = await Add_Package({
            ...data.request,
            discount:data.request.discount.toString(),
            begintime: dayjs(data.request.begintime).format('YYYY-MM-DD'),
            endtime: dayjs(data.request.endtime).format('YYYY-MM-DD')
        })
        if (res.code === Api_Code.ok) {
            closeloading()
            msg(res)
        }else{
            closeloading()
            msg(res)
        }

    },
    //上传失败的回调 
    handleError(error: Error, file: UploadFile) {
        ElMessage.error('上传失败');

    },
    //上传成功回调
    handleSuccess(response: any, file: UploadFile) {
        ElMessage.success('上传成功');
        console.log(response, ":::::::::")
        response.data.map((path: string) => {
            data.request.pimg.push(path.split('images/').pop());
        })
       
    },
    discount() {
        let sum = 0;
        data.request.product.forEach((d: any) => {
            sum += d.pprice
        });
        data.request.total_price = (sum * data.request.discount).toFixed(2)//保留两位小数
    },
    //获取选中的产品
    async save() {
        startloading()
        data.request.pids = treeRef.value!.getCheckedKeys(true)
        if(data.request.pids.length<2){
            ElMessage.error('请至少选择两个产品')
            closeloading()
            return
        }
        const res = await Getpro({
            ids: data.request.pids
        })
        if (res.code === Api_Code.ok) {
            data.request.product = res.data
            console.log(data.request.product)
            data.isEdit = false
            data.isdiscount = false
            closeloading()
        }

    },

    //选中框的事件
    select() {
        data.isButton = false
        data.isFisrt = true
    },
    //绑定产品树组件
    async pro() {
        data.isFisrt = true
        data.isEdit = true
        data.request.discount = ""
        const res = await Get_tree_package({
            id: data.pid!.toString()
        })
        if (res.code === Api_Code.ok) {
            data.request.props = res.data
            data.isFisrt = false
        }
    },

    handleClose(done: any) {
        ElMessageBox.confirm('确定要退出吗?')
            .then(() => {
                done()
            })
            .catch(() => {
                // catch error
            })
    }
}

const methods = {

    async bind() {
        const res = await Get_Product_Type()
        if (res.code === 0) {
            data.options = res.data
        }

    }
}

onMounted(async () => {
    await methods.bind()
})
</script>



<style scoped></style>